package com.chaosj.skill.discovery.registry

import com.chaosj.config.seata.ConfigChangeListener
import com.chaosj.config.seata.Configuration
import com.chaosj.config.seata.ConfigurationFactory
import org.springframework.util.StringUtils

/**
 * @Description:
 * @author: caoyangjie
 * @date: 2019年12月2019/12/23日 17:18
 * @Copyright: © 赢时胜
 */
class FileRegistryServiceImpl implements IRegistryService<ConfigChangeListener> {
    private static volatile FileRegistryServiceImpl instance
    private static final Configuration CONFIG = ConfigurationFactory.getInstance()
    private static final String POSTFIX_GROUPLIST = ".grouplist"
    private static final String ENDPOINT_SPLIT_CHAR = ""
    private static final String IP_PORT_SPLIT_CHAR = ":"

    private FileRegistryServiceImpl() {
    }

    /**
     * Gets instance.
     *
     * @return the instance
     */
    static FileRegistryServiceImpl getInstance() {
        if (null == instance) {
            synchronized (FileRegistryServiceImpl.class) {
                if (null == instance) {
                    instance = new FileRegistryServiceImpl()
                }
            }
        }
        return instance
    }

    @Override
    void register(InetSocketAddress address) throws Exception {

    }

    @Override
    void unregister(InetSocketAddress address) throws Exception {

    }

    @Override
    void subscribe(String cluster, ConfigChangeListener listener) throws Exception {

    }

    @Override
    void unsubscribe(String cluster, ConfigChangeListener listener) throws Exception {

    }

    @Override
    List<InetSocketAddress> lookup(String key) throws Exception {
        String clusterName = getServiceGroup(key)
        if (null == clusterName) {
            return null
        }
        String endpointStr = CONFIG.getConfig(
                PREFIX_SERVICE_ROOT + CONFIG_SPLIT_CHAR + clusterName + POSTFIX_GROUPLIST)
        if (!StringUtils.hasText(endpointStr)) {
            throw new IllegalArgumentException(clusterName + POSTFIX_GROUPLIST + " is required")
        }
        String[] endpoints = endpointStr.split(ENDPOINT_SPLIT_CHAR)
        List<InetSocketAddress> inetSocketAddresses = new ArrayList<>()
        for (String endpoint : endpoints) {
            String[] ipAndPort = endpoint.split(IP_PORT_SPLIT_CHAR)
            if (ipAndPort.length != 2) {
                throw new IllegalArgumentException("endpoint format should like ip:port")
            }
            inetSocketAddresses.add(new InetSocketAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1])))
        }
        return inetSocketAddresses
    }

    @Override
    void close() throws Exception {

    }

}
